<?php

namespace Biz\model\brand;

use Doraemon\model\ShortLink\ShortLink as mShortLink;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\LinkFormat;

class BrandLink extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_store';

    const _CONFIG_SELECT_ = 'db_store';

    const _DATABASE_ = 'store';

    const _TABLE_NAME = 'brand_link';

    const SHORT_PREFIX = 'http://l.hhz1.cn/';

    public static function getInfo($where, $select = '*')
    {
        return self::get($select, $where);
    }

    public static function selectList($where, $select = '*')
    {
        $list = self::select($select, $where);
        return $list;
    }

    public static function selectCount($where)
    {
        $count = self::count('id', $where);
        return $count;
    }

    public static function insertData($data)
    {
        if (!isset($data['addtime'])) {
            $data['addtime'] = date('Y-m-d H:i:s');
        }
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return self::id();
    }

    public static function updateData($data, $where)
    {
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }


    public static function createShortLink($brandId, $uid)
    {
        $shortLink = '';
        $info = self::getInfo(['brand_id' => $brandId]);
        if (!empty($info) && $info['short_link']) {
            $shortLink = $info['short_link'];
        } else {
            $longLink = Hhzurl::h5BrandPerson($uid);
            $linkParams = ['user_id' => $uid, 'tab' => 0];
            $url = LinkFormat::generateLink(LinkConf::LINK_USER_DETAIL, json_encode($linkParams));
            $longLinkApp = $url ? $url[LinkConf::TEMPLATE_TYPE_APP] : '';

            $shortLinkData = [
                'long_link' => $longLink,
                'long_link_app' => $longLinkApp,
                'short_link' => '',
                'reason' => '品牌号-品牌名称',
                'department' => '其他',
                'address' => '品牌号',
                'admin_id' => 0,
                'addtime' => time(),
                'status' => 1,
            ];
            $id = mShortLink::insertData($shortLinkData);
            $shortLink = mShortLink::createShortLink($id, $longLink, $longLinkApp);
            if ($info) {
                self::updateData(['short_link' => $shortLink], ['brand_id' => $brandId]);
            } else {
                self::insertData(['short_link' => $shortLink, 'brand_id' => $brandId]);
            }
        }
        return $shortLink;

    }
}